package com.qf.servlet;

import com.qf.model.User;
import com.qf.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

@WebServlet("/regist")

public class RegistServlet extends HttpServlet {
    private UserServiceImpl userService = new UserServiceImpl();
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String sex = req.getParameter("sex");
        String phone = req.getParameter("phone");
        String money = req.getParameter("money");
        User user = new User();
        user.setPhone(phone);
        user.setUsername(username);
        user.setSex(Integer.parseInt(sex));
        user.setPassword(password);
        user.setMoney(0.0);
        user.setCreateTime(new Date());
        boolean isok = userService.regist(user);
        // 开始响应
        PrintWriter writer = resp.getWriter();
        if (isok) {// 注册成功,跳转登录页面重新登录
            // writer.write("<html>");
            // writer.write("<head>");
            // writer.write("<title>注册成功</title>");
            // writer.write("</head>");
            // writer.write("<body>");
            // writer.write("<h1 style='color:green'>注册成功</h1>");
            // writer.write("</body>");
            // writer.write("</html>");

            // 请求转发
            // req.getRequestDispatcher("/qf_login.html").forward(req,resp);

            // 响应重定向跳转页面
            resp.sendRedirect("/qf_login.html");
        } else {
            // writer.write("<html>");
            // writer.write("<head>");
            // writer.write("<title>注册失败</title>");
            // writer.write("</head>");
            // writer.write("<body>");
            // writer.write("<h1 style='color:red'>注册失败</h1>");
            // writer.write("</body>");
            // writer.write("</html>");

            // 注册失败,跳转失败页面
            req.getRequestDispatcher("/error.html").forward(req,resp);
        }
    }
}
